<template>
  <a-modal
    title="项目部人员设置"
    :width="960"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout" :rules="rules">
        <div>
          <a-row :gutter="24">
            <a-col :md="12" :sm="12">
              <a-form-item
                label="调入人员名称"
                :labelCol="{lg: {span: 7}, sm: {span: 7}}"
                :wrapperCol="{lg: {span:17}, sm: {span: 17} }">
                <a-select :mode="selectMode"
                          :allowClear="true"
                          show-search
                          placeholder="根据员工姓名搜索"
                          :not-found-content="fetching ?undefined : null"
                          @search="handleSearchStaff"
                          @focus="getProjectStaff"
                          v-model="employees"
                          @popupScroll="scrollMore"
                          :filter-option="filterOption"
                          @change="getStaffInfo"
                          labelInValue
                          @deselect="deselectStaff">
                  <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                  <a-select-option v-for="item in staffs" :key="item.id" :value="item.id">{{item.name }}({{item.jobNum}})</a-select-option>
                </a-select>

              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <a-table :loading="loadingState.isTable" :columns="columns" :data-source="dataSource" bordered :pagination="false"></a-table>
              <pagination
                      :total="totalSize"
                      v-model="pageNo"
                      :pageSize.sync="pageSize"
                      @change="handlePageChange"
                      @showSizeChange="showSizeChange"
              ></pagination>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :md="24" :sm="24">
              <div>
                *备注：该人员之前的项目岗位权限，将在项目立项成功15天后，自动取消。
              </div>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getProjectStaff,getInfoByStaffId,getOrgUsers,getEmployeesList } from '@/api/commons'
import { getJobEmployee } from '@/api/project/projects'

// 表单字段
const fields = ['employee']

const columns = [
  {
    title: '员工名称',
    dataIndex: 'employeeName',
  },
  {
    title: '员工编号',
    dataIndex: 'employeeNum',
  },
  {
    title: '所在单位',
    dataIndex: 'branch',
  },
  {
    title: '所在部门',
    dataIndex: 'projectName',
  },
  {
    title: '当前岗位',
    dataIndex: 'jobName',
  }
]
export default {
  name:'a'+Date.now(),
  props: {
    // 兼容 额外查询条件
    extraQuery: {
      type: Object,
      default: () => {}
    },
    visible: {
      type: Boolean,
      required: true
    },
    employeeNums:{
      type: String,
      default: () => null
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    multi:{
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    dataSourceProp: {
      type: Array,
      default: () => []
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      loadingState: {
        isTable: false
      },
      columns,
      dataSource:[],

      totalSize: 0,
      totalPage:0,
      pageNo: 1,
      pageSize: 10,

      pageNumber:1,   // 调入人员分页
      pageSize1:20,    // 调入人员分页数量
      totalPages:0,    // 总页数
      totalSize1:0,    // 总数

      groupName:'',
      groupDatas: [{value: 2,text: '新增'},{value: 0,text: '更换'},{value: 1,text: '移除'}],

      isReplace:false,  // 是否显示被更换人员
      isRemove:false,   // 是否显示被移除人员
      isShow:false,     // 新增
      selectMode: 'default', //选择模式
      isMulti: false,//是否可多选
      form: this.$form.createForm(this),
      rules: {
        employee: [{ required: true, message: '请选择人员'}],
      },
      employees:[],
      employeeIds:[],
      fetching: false,//获取人员信息
      staffs:[],   // 调入人员名称

      staffCode:'',  //员工编号
      branchName:'', //调用人员分公司
      projectName:'', // 所在项目
      jobName:'',   // 当前岗位
      selectedStaffs: {} //当前选中的人员
    }
  },
  created () {
  },
  watch:{
    dataSourceProp: {
      immediate: true,
      handler(val) {
        this.dataSource = val || []
      }
    },
    multi:{
      handler: function(val){
        this.selectMode = val?'multiple':'default'
        this.isMulti = !!val
      }
    },
    model:{
      handler: function(val){
        if(this.isMulti) {
          this.employees = []
        } else {
          this.employees = {}
        }
        if(val){
          this.selectedStaffs={}
          this.pageNumber = 1
          this.totalSize = 0
          this.totalPage = 0
          this.pageNo = 1
          this.pageSize = 10
          // 编辑人员回显选中
          val.staffList.forEach(item => {
            if(this.isMulti) {
            this.employees.push({
              key: item.employeeId,
              label: item.staffName
            })
            } else {
              this.employees = {
                key: item.employeeId,
                label: item.staffName
              }
            }
          })
          this.getStaffInfo()
        }else{
          this.totalSize = 0
          this.totalPage = 0
          this.pageNo = 1
          this.pageNumber = 1
          this.pageSize = 10
          this.employeeIds=[]
          this.selectedStaffs={}
        }

      },
      deep: true
    }
  },
  methods:{
    handleSearchStaff(val) {
      this.pageNumber = 1
      this.getProjectStaff(val)
    },
    // 下拉滚动加载
    scrollMore(e) {
      const { target } = e
      var total = target.scrollTop + target.offsetHeight
      var scrollHeight = target.scrollHeight

      // this.pageNo是当前页 this.totalPage是总页数
      if (total >= scrollHeight - 3 && total < scrollHeight + 3 && this.pageNumber <= this.totalPages ) {
        this.pageNumber = this.pageNumber + 1
        this.getProjectStaff () // 调用api方法
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.getStaffInfo()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.getStaffInfo()
    },

    deselectStaff(value){
      this.staffs.forEach(s=>{
        if(s.id===value.key){
          delete this.selectedStaffs[value.key];
        }
      })
    },
    // 查询调入人员
    getProjectStaff(value){
      this.fetching = true;
      // 不查询已删除人员  delete: 0
      getOrgUsers({key:value?value:'',pageNumber: this.pageNumber,pageSize: value ? 99999 : this.pageSize1, delete: 0, ...this.extraQuery }).then(res=>{
        if(res.data){
          // 去重, 如果已存在，则不再添加
          let data = []
          res.data && res.data.forEach(item => {
            if (!this.staffs.filter(itemc => item.id == itemc.id).length) {
              data.push(item)
            }
          })
          this.staffs  = this.staffs.concat(data)
        }
        this.totalPages = res.totalPages
        this.totalSize1 = res.totalSize
        this.fetching = false;
      }).catch(()=>{
        this.fetching = false;
      })
    },
    getStaffInfo(){
      try {
      if(!this.employees && !this.employees.length || !this.isMulti && !Object.keys(this.employees).length) {
        this.$emit('employeeNums', '');
        this.$emit('employees', []);
        return
      }
      } catch(e) {
        console.error(e)
        this.$emit('employeeNums', '');
        this.$emit('employees', []);
        return
      }
      if(this.multi){
        const jobNums = []
        this.staffs.forEach(staff => {
          const targetStaff = this.employees.find(item => item.key === staff.id)
          targetStaff && jobNums.push(staff.jobNum)
        })
        this.staffCode = jobNums.join(',')
        let arr = []
        if(this.employees.length !=0 ){
          this.employees.forEach(function(obj,i) {
            arr.push(obj.key)
          })
        }
        this.dataSource = []
        if(arr.length > 0){
          this.loadingState.isTable = true
          getJobEmployee({ids:arr,projectAuditStatus:2,employeeStatus:0, pageSize: this.pageSize, pageNo: this.pageNo}).then(res=>{
            this.loadingState.isTable = false
            this.dataSource = res.data
            this.totalSize = res.totalSize
            this.totalPage = res.totalPage
            this.$emit('dataSources',this.dataSource)
          }).catch(() => {
            this.loadingState.isTable = false
          })
        }


        this.$emit('employeeNums',this.staffCode);
        this.$emit('employees',this.employees.map(item => {
          const staffTarget = this.staffs.find(staffItem => staffItem.id === item.key)
          return {
            ...item,
            employeeNum: staffTarget && staffTarget.jobNum || ''
          }
        }))
      }else{
        this.employees = this.employees || {}
        const staffTarget = this.staffs.find(item => item.id === this.employees.key)
        if(staffTarget) {
          this.selectedStaffs[this.employees.key] = staffTarget
          this.staffCode = staffTarget.jobNum
          this.$emit('employeeNums', staffTarget.jobNum)
          this.$emit('employees', [{key:  staffTarget.id, label: staffTarget.name, employeeNum: staffTarget.jobNum }])
        } else {
          this.$emit('employeeNums', '')
          this.$emit('employees', [])
        }
        let arr = []
        arr.push(this.employees.key)

        this.dataSource = []
        if(arr.length > 0){
          this.loadingState.isTable = true
          getJobEmployee({ids:arr,projectAuditStatus:2,employeeStatus:0, pageSize: this.pageSize, pageNo: this.pageNo}).then(res=>{
            this.loadingState.isTable = false
            this.dataSource = res.data
            this.totalSize = res.totalSize
            this.totalPage = res.totalPage
          }).catch(() => {
            this.loadingState.isTable = false
          })
        }
      }
    },
  }
}
</script>
